<?php
/*
 * Authorize.net Payment Plugin Class
 */
class RM_Plugin_AuthorizeNet extends RM_Payments_Plugin
{    
    /**
     * distination for posting the payment data
     * @var sting
     */
    private $_live_post_url = "https://secure.authorize.net/gateway/transact.dll";
    private $_test_post_url = "https://test.authorize.net/gateway/transact.dll";

    private $_ipnLog = true; // logging enabled

    /**
     * Public constructor
     */
    public function  __construct() {
        $this->name = 'AuthorizeNet';
        $this->_ipnLogFile = RM_Environment::getConnector()->getCorePath().DIRECTORY_SEPARATOR.'userdata'.DIRECTORY_SEPARATOR.'logs'.DIRECTORY_SEPARATOR.'authorizenet_log.txt';

        
    }

    /**
     * collects the payment data and sends to Authrize.net
     */
    public function Process($bookingRef, $ccArray, $userData){

        if (empty($ccArray) || empty($userData)) return false;

        $settings = $this->_getConfig();

        // set the standard params for the transaction...
        $postarray = array(
            "x_login" => $settings['api_id'],
            "x_tran_key" => $settings['trans_key'],
            "x_version"	=> "3.1",
            "x_delim_data" => "TRUE",
            "x_delim_char" => "|",
            "x_relay_response" => "FALSE",
            "x_method" => "CC"
        );

        if ((int)$settings['test_mode'] === 1){
            $postURL = $this->_test_post_url;
            $postarray["x_test_request"] = true;
        } else {
            $postURL = $this->_live_post_url;
        }
        

        // if pre-authorize is set then just set the Authorize only type
        if ($settings['pre_authorize']===1){
            $postarray["x_type"] = "AUTH_ONLY";
        } else {
            $postarray["x_type"] = "AUTH_CAPTURE";
        }
        
        // card details...
        $postarray["x_card_num"] = $ccArray['x_card_num'];
        $postarray["x_exp_date"] = $ccArray['x_exp_date'];
        $postarray["x_amount"] = $ccArray['x_amount'];
        $postarray["x_description"] = $ccArray['x_description'];
        $postarray["x_card_code"] = $ccArray['x_card_code'];
        $postarray["x_invoice_num"] = $bookingRef;

        $config = new RM_Config();
        $currencyCode = $config->getValue('rm_config_currency_iso');
        $postarray["x_currency_code"] = $currencyCode;


        // user details...
        $postarray["x_first_name"] = $userData['first_name'];
        $postarray["x_last_name"] = $userData['last_name'];
        $postarray["x_address"] = $userData['address'];
        $postarray["x_state"] = $userData['state'];
        $postarray["x_zip"] = $userData['zip'];
        $postarray["x_country"] = $userData['country'];

        // send the request with the data...
        $client = new Zend_Http_Client($postURL);
        $client->setParameterPost($postarray);
        $response = $client->request("POST");

        $response_array = explode($postarray["x_delim_char"],$response);

        $this->_logResults("------ Transaction Started ------");
        
        $responseData['ResponseCode'] = (int)$response_array[1];
        $responseData['ResponseReasonCode'] = $response_array[2];
        $responseData['ResponseReasonText'] = $response_array[3];
        $responseData['AuthorizationCode'] = $response_array[5];
        $responseData['TransactionID'] = $response_array[6];
        $responseData['BookingRef'] = $response_array[7];
        $responseData['Amount'] = $response_array[9];
        $responseData['TransactionType'] = $response_array[11];
        
        foreach ($responseData as $key=>$value){
            $this->_logResults($key.": ".$value);
        }
        $this->_logResults("------ Transaction Ended ------");

        // now send back the response...
        return $responseData;
    }

    /**
     * We don't need to present this plugins under admin tree menu 'Plugins', only on Config leaf
     * 
     * @return null
     */
    public function getNode(){
        return null;
    }


    /**
     * get the authorize.net config
     *
     * @return   array
     */
    private function _getConfig() {
        $authorizenetObj = new RM_AuthorizeNet;
        $value = $authorizenetObj->getSettings()->toArray();
        return $value[0];
    }

    /**
     * used to log results to the ipn log file so we can see whats happening
     *
     * @param boolean $success if this is a successful or fail log
     */
    private function _logResults($msg)
    {
        if (!$this->_ipnLog) return;  // is logging turned off?

        // Timestamp
        $text = '['.date('m/d/Y g:i A').'] - ';
        $text .= $msg;

        // Write to log
        $fp = fopen($this->_ipnLogFile, 'a');
        fwrite($fp, $text . "\n\n");
        fclose($fp);  // close file
    }
}